package com.java.reflection;

import com.java.reflection.test.Child;

import java.lang.reflect.Field;

public class FieldAPI {
    // Class中与Field相关的API：getFields、getField、getDeclaredFields、getDeclaredField
    public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, IllegalAccessException, InstantiationException {
        Class<?> childCls = Class.forName("com.java.reflection.test.Child");
        Child childIns = (Child) childCls.newInstance();
        Field childPublicField = childCls.getField("childPublicVar");
        
        // set：设置成员属性值
        childPublicField.set(childIns, "OuterChildPublicVar");
        
        // get：获取成员属性值
        System.out.println(childPublicField.get(childIns)); // OuterChildPublicVar
        
        // setAccessible：参数为true表示抑制访问检查，暴力访问私有成员属性
        Field childPrivateField = childCls.getDeclaredField("childPrivateVar");
        childPrivateField.setAccessible(true);
        childPrivateField.set(childIns, "OuterChildPrivateVar");
        System.out.println(childPrivateField.get(childIns)); // OuterChildPrivateVar
        
        // getDeclaringClass：获取成员属性所在的类的Class实例
        System.out.println(childPublicField.getDeclaringClass()); // class com.java.reflection.test.Child
        
        // getName：获取成员属性名
        System.out.println(childPublicField.getName()); // childPublicVar
        
        // getType：Class形式获取成员属性的类型
        System.out.println(childPublicField.getType()); // class java.lang.String
        
        // toGenericString：获取成员属性的详细信息
        System.out.println(childPublicField.toGenericString()); // public java.lang.String com.java.reflection.test.Child.childPublicVar
        
        // isEnumConstant：判断成员属性是否为枚举类型
        System.out.println(childPublicField.isEnumConstant()); // false
    }
}
